package com.example.tosco;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class HistoricoDAO {
	private SQLiteDatabase db;
	private Helper helper;
	private String[] columns = {"_id", "data", "hora", "texto"};
	
	public HistoricoDAO(Context context)
	{
		helper = new Helper(context);
	}
	
	public void open() throws SQLException
	{
		db = helper.getWritableDatabase();
	}
	
	public void close()
	{
		db.close();
	}

	public Historico addHistorico(Historico h)
	{
		ContentValues values = new ContentValues();
		values.put("data", h.getData());
		values.put("hora", h.getHora());
		values.put("texto", h.getTexto());
		
		long insertId = db.insert("Historico", null, values);
		Cursor cursor = db.query("Historico", columns, "_id = " + insertId, null, null, null, null);
		
		cursor.moveToFirst();
		Historico newHistorico= cursorToHistorico(cursor);
		cursor.close();
		
		return newHistorico;
	}
	
	public List<Historico> getLista()
	{
		List<Historico> historico = new ArrayList<Historico>();
		
		Cursor cursor = db.query("Historico", columns, null, null, null, null, null);
		
		cursor.moveToFirst();
		while(!cursor.isAfterLast())
		{
			historico.add(cursorToHistorico(cursor));
			cursor.moveToNext();
		}
		
		cursor.close();
		return historico;
	}
	
	private Historico cursorToHistorico(Cursor cursor)
	{
		Historico hist = new Historico();
		
		hist.setId(cursor.getLong(0));
		hist.setData(cursor.getString(1));
		hist.setHora(cursor.getString(2));
		hist.setTexto(cursor.getString(3));
		
		return hist;
	}
}
